/*
 * @lc app=leetcode.cn id=25 lang=java
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start

import java.util.List;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        int count = 0;
        ListNode temp = head;
        while(temp != null) {
            count++;
            temp = temp.next;
            if(count == k-1) {
                break;
            }
        }

        if(temp == null) {
            return head;
        }

        int num = k;
        temp = temp.next;

        ListNode dummy = head;
        ListNode pre = null;
        while(num != 0) {
            ListNode cur = head.next;
            head.next = pre;
            pre = head;
            head = cur;
            num--;
        }

        dummy.next = reverseKGroup(temp, k);
        return pre;
    }
}
// @lc code=end

